﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASPNETPerformance.App_BusinessLogic.BasePages;
using ASPNETPerformance.App_BusinessLogic.Cache;

namespace ASPNETPerformance._06_Cache {
    public partial class FileCache : BasePage {
        protected void Page_Load( object sender, EventArgs e ) {
            if ( !this.Page.IsPostBack ) {
                BindData();
            }
        }

        private void BindData() {
            DataTable dt = null;
            string cacheKey = "TestFileCache";

            var data = ( DataTable )Global.FileCache[ cacheKey ];

            if ( data == null ) {
                Trace.Warn( "数据不在FileCache中" );
                dt = GetProductsByAll();
                Global.FileCache.Add( cacheKey, dt, DateTime.Now.AddMinutes( 10 ) );
            }
            else {
                Trace.Warn( "数据在FileCache中" );
                dt = data;
            }

            this.GridView1.DataSource = dt;
            this.GridView1.DataBind();
        }

        private DataTable GetProductsByAll() {
            DataTable productsTables = new DataTable();
            SqlConnection conn =
                new SqlConnection( ConfigurationManager.ConnectionStrings[ "NorthwindConnectionString" ].ConnectionString );
            SqlDataAdapter cmd = new SqlDataAdapter( "SELECT Products.ProductName, Categories.CategoryName, Suppliers.CompanyName, Products.QuantityPerUnit, Products.UnitPrice, Products.Discontinued FROM Products INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID INNER JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID ORDER BY Products.ProductName", conn );
            productsTables = new DataTable( "ProductsByAll" );
            cmd.Fill( productsTables );
            return productsTables;
        }
    }
}